package com.vpen.base;


import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

import java.io.Serializable;



/**
 * @version: 1.0
 * @author: Vpen
 * @date: 2021/10/2 23:24
 * @content: 统一返回结果
 */
@Data
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = true)
public class BaseResult<T> extends BaseMsg implements Serializable {
    private static final long serialVersionUID = 1765745297345L;
    private T data;

    public BaseResult(String code, String msg) {
        super(code, msg);
    }

    public BaseResult(String code, String msg, T data) {
        super(code, msg);
        this.data = data;
    }

    /**
     * 成功返回
     *
     * @return com.vpen.base.BaseResult<T>
     * @author 韦鹏
     * @date 2021/10/3 0:12
     * @name ok
     **/
    public static BaseResult<Boolean> ok() {
        return create(BaseCode.SUCCESS, true);
    }

    public static <T> BaseResult<T> ok(T data) {
        return create(BaseCode.SUCCESS, data);
    }

    public static <T> BaseResult<T> ok(String code, String msg, T data) {
        return create(code, msg, data);
    }


    /**
     * 失败返回
     *
     * @return com.vpen.base.BaseResult<T>
     * @author 韦鹏
     * @date 2021/10/3 0:11
     * @name error
     **/
    public static BaseResult<Boolean> error() {
        return create(BaseCode.ERROR, false);
    }

    public static <T> BaseResult<T> error(T data) {
        return create(BaseCode.ERROR, data);
    }

    public static <T> BaseResult<T> error(String code, String msg, T data) {
        return create(code, msg, data);
    }


    /** 自动判断
     * @author 韦鹏
     * @date 2021/10/3 0:54
     * @name auto
     * @param flag flag
     * @param ok ok
     * @param error error
     * @return com.vpen.base.BaseResult<T>
     **/
    public static <T> BaseResult<T> auto(boolean flag, T ok, T error) {
        return flag ? ok(ok) : error(error);
    }

    public static  BaseResult<Boolean> auto(boolean flag) {
        return flag ? ok() : error();
    }


    /**
     * 创建
     *
     * @param code code
     * @param msg  msg
     * @param data data
     * @return com.vpen.base.BaseResult<T>
     * @author 韦鹏
     * @date 2021/10/3 0:23
     * @name create
     **/
    private static <T> BaseResult<T> create(String code, String msg, T data) {
        return new BaseResult<>(code, msg, data);
    }

    private static <T> BaseResult<T> create(String code, String msg) {
        return new BaseResult<>(code, msg, null);
    }

    private static <T> BaseResult<T> create(BaseCode baseCode, T data) {
        return create(baseCode.getCode(), baseCode.getMsg(), data);
    }

    private static BaseResult<Boolean> create(BaseCode baseCode, boolean flag) {
        return new BaseResult<>(baseCode.getCode(), baseCode.getMsg(), flag);
    }

}
